package com.guang.elegantshutdowm.executor;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ CopyFilePageSafelyDestroyExecutorProperties.class})
public class ExecutorConfig {


    @Bean({"copyFilePageSafelyDestroyExecutor"})
    @ConditionalOnClass({CopyFilePageSafelyDestroyExecutor.class})
    public CopyFilePageSafelyDestroyExecutor copyFilePageSafelyDestroyExecutor(CopyFilePageSafelyDestroyExecutorProperties copyFilePageSafelyDestroyExecutorProperties) {
        CopyFilePageSafelyDestroyExecutor copyFilePageSafelyDestroyExecutor = new CopyFilePageSafelyDestroyExecutor();
        copyFilePageSafelyDestroyExecutor.setCorePoolSize(copyFilePageSafelyDestroyExecutorProperties.getCorePoolSize());
        copyFilePageSafelyDestroyExecutor.setMaxPoolSize(copyFilePageSafelyDestroyExecutorProperties.getMaxPoolSize());
        copyFilePageSafelyDestroyExecutor.setQueueCapacity(copyFilePageSafelyDestroyExecutorProperties.getQueueCapacity());
        copyFilePageSafelyDestroyExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        copyFilePageSafelyDestroyExecutor.setThreadFactory(new ThreadFactory() {
            private final String THREAD_PREFIX = "CopyFilePageSafelyDestroyExecutor_";
            private final AtomicInteger atomicInteger = new AtomicInteger(1);
            public Thread newThread(Runnable r) {
                return new Thread(r, THREAD_PREFIX + this.atomicInteger.getAndIncrement());
            }
        });
        return copyFilePageSafelyDestroyExecutor;
    }

}